package com.aerfafish.spider.neo4j.spider.service.impl;

import com.aerfafish.spider.neo4j.dao.FundValue;
import com.aerfafish.spider.neo4j.repository.DateRepository;
import com.aerfafish.spider.neo4j.repository.FundValueRepository;
import com.aerfafish.spider.neo4j.spider.service.FundDateRelationService;
import org.neo4j.driver.exceptions.TransientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.stereotype.Service;

/**
 * @author aerfafish
 * @date 2021/4/22 11:21 上午
 */
@Service
public class FundDateRelationServiceImpl implements FundDateRelationService {

    @Autowired
    FundValueRepository fundValueRepository;

    @Autowired
    DateRepository dateRepository;

    @Override
    public void save(FundValue fundValue) throws Exception {
        save(fundValue, fundValue.getFund().getCode(), fundValue.getDate().getDate());
    }

    @Override
    public void save(FundValue fundValue, String fundCode, String date) throws Exception {
        save(fundCode, date, fundValue.getAverageValue(), fundValue.getAccumulatedValue(),
                fundValue.getDailyGrowthRate(), fundValue.getSubscriptionStatus(),
                fundValue.getRedemptionStatus());
    }

    @Override
    public void save(String fundCode, String date, Float averageValue, Float accumulatedValue,
                     Float dailyGrowthRate, String subscriptionStatus, String redemptionStatus) throws Exception {
        if (fundCode == null || date == null || averageValue == null || accumulatedValue == null ||
                dailyGrowthRate == null || subscriptionStatus == null || redemptionStatus == null) {
            throw new Exception("fundCode:" + fundCode + " date: " + date + " param is null");
        }

        try {
            fundValueRepository.save(fundCode, date, averageValue, accumulatedValue, dailyGrowthRate,
                    subscriptionStatus, redemptionStatus);
        } catch (TransientException | InvalidDataAccessApiUsageException e) {
            try {
                fundValueRepository.save(fundCode, date, averageValue, accumulatedValue, dailyGrowthRate,
                        subscriptionStatus, redemptionStatus);
            } catch (TransientException | InvalidDataAccessApiUsageException e0) {
                fundValueRepository.save(fundCode, date, averageValue, accumulatedValue, dailyGrowthRate,
                        subscriptionStatus, redemptionStatus);
            }
        }

    }
}
